/*
 * VariableAst.cpp
 *
 *  Created on: 1 Nov 2010
 *      Author: kn308
 */

#include <iostream>
#include <MAlice/Codegen.h>
#include <MAlice/Ast/VariableAst.h>
#include <MAlice/Ast/IntegerLiteralAst.h>

namespace MAlice
{

VariableAst::VariableAst(const string& name) :
	mParam(false), mName(name), mOffset(new IntegerLiteralAst(0))
{
}

VariableAst::VariableAst(const string& name, ExpressionAst* offset) :
	mParam(false), mName(name), mOffset(offset)
{
}

VariableAst::~VariableAst()
{
	delete mOffset;
}

Value* VariableAst::getPointer()
{
#	ifndef NDEBUG
	cout << "VariableAst::getPointer()" << endl;
#	endif
	Codegen* g = Codegen::get();

	// get the i-th element of the pointer
	if (Value* value = g->getVar(getName()))
		return g->getBuilder()->CreateGEP(value, mOffset->generate());
	else
		throw runtime_error(getName() + " is not defined!");
}

Value* VariableAst::generate()
{
#	ifndef NDEBUG
	cout << "VariableAst::generate()" << endl;
#	endif

	Builder* builder = Codegen::get()->getBuilder();
	Value  * pointer = getPointer();

	return builder->CreateLoad(pointer, mName);
}

}
